import 'dart:io';

import 'package:star_author/controller/backflow_getx_controller.dart';
import 'package:star_author/controller/categories_getx_controller.dart';
import 'package:star_author/provider/config.dart';
import 'package:star_author/utils/common_util/log_util.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_keys_constant.dart';
import 'package:star_author/utils/common_util/shared_preferences/sp_util.dart';
import 'package:star_author/utils/http/api_manager.dart';
import 'package:star_author/utils/http/http_util.dart';
import 'package:star_author/views/anchor/home_page.dart';
import 'package:star_author/views/splash_page/splash_ad_util.dart';
import 'package:star_author/views/splash_page/splash_advertisement_widget.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:provider/provider.dart';

import '../../controller/featured_services_controller.dart';

class SplashPage extends StatefulWidget {
  static String routeName = '/';

  const SplashPage({Key? key}) : super(key: key);

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  bool isExistAdImage = false;

  bool isAdFinish = false;

  Map? adImageInfo;

  int indexTab = 0;

  final backflowController = Get.put(BackflowGetXController());

  @override
  void initState() {
    super.initState();
    Get.put(CategoryController());
    Get.put(FeaturedServicesController());
    initPage();
  }

  void initPage() async {
    if (Platform.isAndroid) {
      HttpUtil.commonRequest(
        Get.context!,
        "/api/v1/msa_certificate",
        isLoading: false,
        isErrorToast: false,
      ).then((value) async {
        SpUtil.putString(SpKeysConstant.oaid_sdk_cert, value.data['data']);
        LogUtil.v("更新证书-${value.data['data']}");
      }).catchError((e) {
        LogUtil.v('e:${e.toString()}');
      });
    }

    HttpUtil.commonRequest(Get.context!, ApiManager.settings,
            isLoading: false, isErrorToast: false)
        .then((value) {
      Provider.of<ConfigProvider>(Get.context!, listen: false)
          .set(key: "settings", value: value.data);

      Map adImageInfo = {
        "image": value.data['splash_ad_image_url'] ?? "",
        "page": value.data['splash_ad_jump_path'] ?? "",
        "colors": value.data['splash_ad_colors'] ?? [],
        "is_open": false,
      };

      if (value.data['splash_ad_image_url'] != null &&
          value.data['splash_ad_image_url'].isNotEmpty) {
        adImageInfo['is_open'] = true;
        LogUtil.v('adImageInfo$adImageInfo');
        SplashAdUtil.setAdImageLocalInfo(adImageInfo);
      }

      SplashAdUtil.checkIfShouldDownloadAdImage(adImageInfo);

      IndexPageHandler.setAppConfig(value.data);
    }).catchError((e) {
      LogUtil.v("e;${e.toString()}");
    });

    bool isAgree = SpUtil.getBool(SpKeysConstant.agree, defValue: false)!;
    if (isAgree == false) {
      await Future.delayed(Duration(milliseconds: 1500));
      jump2Page();
      return;
    }

    SplashAdUtil.getAdImageLocalInfo().then((info) async {
      if (info != null) {
        adImageInfo = info;

        String path = await SplashAdUtil.getAdImagePath(info);
        LogUtil.v('path-------->$path');

        isExistAdImage = await File(path).exists(); //判断广告图片是否存在

        LogUtil.v('isExistAdImage-------->$isExistAdImage');
      } else {
        isExistAdImage = false;
      }

      if (isExistAdImage) {
        setState(() {});
      } else {
        await Future.delayed(Duration(milliseconds: 1500));
        jump2Page();
      }
    });
    HttpUtil.commonRequest(
      Get.context!,
      '/api/v1/basic_flows',
      queryParameters: {
        "classify": "backflow_slideshow",
      },
      isLoading: false,
      isErrorToast: false,
    ).then((value) {
      backflowController.setBannerImageList(value.data['data'] ?? []);
    }).catchError((e) {
      LogUtil.v("e;${e.toString()}");
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        color: Colors.white,
        child: Stack(
          alignment: Alignment.center,
          children: <Widget>[
            Image.asset(
              'images/launch_image_lt.png',
              fit: BoxFit.cover,
            ),
            if (isExistAdImage)
              SplashAdvertisementWidget(
                adImageInfo ?? {},
                (isUserClick) {
                  isAdFinish = true;
                  //页面跳转
                  jump2Page(isJumpAdPage: isUserClick);
                },
              )
          ],
        ),
      ),
    );
  }

  void jump2Page({bool isJumpAdPage = false}) async {
    //黄金回收广告index为2
    if (isJumpAdPage) {
      indexTab = 2;
    }
    if (isJumpAdPage && adImageInfo != null && adImageInfo!['page'] != null) {
      await Future.delayed(Duration(milliseconds: 100));

      Get.toNamed(adImageInfo!['page']);
    }
  }
}
